from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.areas.models import Area


class AreasView(View):
    def get(self, request):
        # 1  去数据库查询所有的省份数据
        try:
            areas = Area.objects.filter(parent=None)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg':"获取省份失败，网络异常"})

        province_list = []

        for a in areas:
            province_list.append({"id": a.id, "name": a.name})

        # 2  返回
        return JsonResponse({'code': 0, 'province_list': province_list})
class SubAreasView(View):
    def get(self, request, area_id):
        # 1 获取路径中的上一级的地区的id
        # 正则校验area_id

        # 2 根据上一级的id获取下一级的数据(数据库操作)
        try:
            subareas = Area.objects.filter(parent_id=area_id)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': "获取市区失败，网络异常"})

        # 3 把下一级数据 做拼接
        subs = []
        for a in subareas:
            subs.append({'id': a.id, 'name': a.name})

        # data.sub_data.subs

        # 4 返回给前端
        return JsonResponse({'code': 0, 'sub_data': {'subs': subs}})
